import React, {useEffect, useRef, useState} from 'react';
import style from './index.module.scss'
import {createRoot} from "react-dom/client";
import {createPortal} from "react-dom";

function MaskInstance(props) {
    let ref = useRef();
    let maskRef = useRef();
    let [s,setState] = useState();
    useEffect(() => {
        onCreate();
        setState(1);
        return ()=>{
            onDestroy()
        }
    },[])
    return (
        <div className={style.MaskContainer} onClick={onClick}>
            <div ref={maskRef} className={style.MaskWrapper}>
            </div>
            {
                props.children &&(
                    <div className={style.MaskElement} ref={ref}>
                        {props.children}
                    </div>
                )
            }
        </div>
    );

    function onClick(event) {
        (props.onClick instanceof Function) && props.onClick();
        if(maskRef.current === event.target) onClickMask()
    }
    function onDestroy() {
        (props.onDestroy instanceof Function) && props.onDestroy();
    }
    function onCreate(){
        (props.onCreate instanceof Function) && props.onCreate();
    }
    function onClickMask(){
        (props.onClickMask instanceof Function) && props.onClickMask();
    }
    function onHide(){}
    function onShow(){}
}

export function Mask(config) {
    if(Mask.defaultContainer === undefined){
        Mask.defaultContainer = document.createElement('div');
        document.body.appendChild(Mask.defaultContainer);
    }
    let maskContainer = document.createElement('div');
    Mask.defaultContainer.appendChild(maskContainer);

    // let por = createPortal(
    //     <MaskInstance onClickMask={destroy}>
    //         {
    //             config.element
    //         }
    //     </MaskInstance>
    //     ,maskContainer)
    // return por
    // console.log(por)
    let mask = createRoot(maskContainer)
    mask.render(
        <MaskInstance onClickMask={destroy}>
            {
                // config.element
                React.cloneElement(config.element, {destroy:destroy})
            }
        </MaskInstance>
    )
    return {
        destroy
    }
    function destroy(){
        mask.unmount();
        maskContainer.remove()
    }
}

export default MaskInstance;